package impl

import (
	"context"
	"fmt"
	"time"

	"gitee.com/shiwjlinux/arm/apps/game"
	"gitee.com/shiwjlinux/arm/common"
	"gitee.com/shiwjlinux/arm/exception"
)

func (i *Impl) SyncGame(ctx context.Context, in *game.SyncGameSet, h game.SyncGameHandleFunc) (*game.Game, error) {
	for _, item := range in.GameItemInfo {
		var ins *game.Game
		var err error

		descGame := game.NewDescribeGameRequestByPackageName(item.PackageName)
		_, err = i.DescribeGame(ctx, descGame)
		if err != nil {
			if err == exception.ErrorNotFound {
				// 创建
				ins, err = i.CreateGame(ctx, item)
			}
		} else {
			updateGame := game.NewUpdateGameRequest()
			updateGame.CreateGameRequest = item
			ins, err = i.UpdateGame(ctx, updateGame)
		}
		if err != nil {
			i.logger.Error().Msgf("create game failed: %v", err)
			h(game.GameResponse{
				Success: false,
				Message: err.Error(),
			})
			continue
		}

		h(game.GameResponse{
			Success: true,
			Message: fmt.Sprintf("%s 同步成功", ins.GameName),
		})

	}
	return nil, nil
}

func (i *Impl) CreateGame(ctx context.Context, in *game.CreateGameRequest) (*game.Game, error) {
	ins := game.NewGame()
	ins.CreateGameRequest = in

	time.Sleep(time.Second)
	if err := i.db.
		Model(&game.Game{}).
		WithContext(ctx).
		Create(ins).Error; err != nil {
		return nil, exception.ErrServerInternal("创建失败")
	}
	return ins, nil
}

func (i *Impl) UpdateGame(ctx context.Context, in *game.UpdateGameRequest) (*game.Game, error) {
	// in.PackageName 不为空
	if err := common.Validate(in); err != nil {
		return nil, exception.ErrorEmpty
	}

	ins := game.NewGame()
	ins.CreateGameRequest = in.CreateGameRequest
	if err := i.db.
		Model(&game.Game{}).
		WithContext(ctx).
		Where("package_name = ?", in.PackageName).
		Updates(ins).Error; err != nil {
		return nil, exception.ErrServerInternal("更新失败")
	}

	return ins, nil
}

func (i *Impl) QueryGame(ctx context.Context, in *game.QueryGameRequest) (*game.GameSet, error) {
	set := game.NewGameSet()
	query := i.db.Model(&game.Game{}).WithContext(ctx)

	if in.GameName != "" {
		query = query.Where("game_name like ?", "%"+in.GameName+"%")
	}
	if in.PackageName != "" {
		query = query.Where("package_name like ?", "%"+in.PackageName+"%")
	}

	if err := query.Count(&set.Total).Error; err != nil {
		return nil, err
	}

	if err := query.
		Offset(in.Offect()).
		Limit(in.PageSize).
		Find(&set.Games).Error; err != nil {
		return nil, exception.ErrServerInternal("查询失败")
	}

	return set, nil
}

func (i *Impl) DescribeGame(ctx context.Context, in *game.DescribeGameRequest) (*game.Game, error) {
	if err := common.Validate(in); err != nil {
		return nil, exception.ErrorEmpty
	}

	ins := game.NewGame()

	query := i.db.Model(&game.Game{}).WithContext(ctx)

	if in.Id != "" {
		query = query.Where("id = ?", in.Id)
	}
	if in.PackageName != "" {
		query = query.Where("package_name = ?", in.PackageName)
	}
	if err := query.First(ins).Error; err != nil {
		return nil, exception.ErrServerInternal("查询失败")
	}

	return ins, nil
}
